GBML manual / Instances

instance_count

How many instances of `obj` are alive right now, counting its children too. Name more objects after the first and it adds them all up: instance_count(obj_orc, obj_bat) is the orcs and the bats together.

Syntax

instance_count(obj, ...more) -> int

Arguments

NameType
objobject
...moreobject (any number of them, none included)

Returns

int

Description

Counts how many instances of an object are alive right now. Handy for a simple wave counter or spawn cap - "don't spawn another enemy while 6 are already on screen", that kind of check - without keeping your own running tally in sync by hand.

If obj is a parent, its children are counted too. With obj_enemy as the parent of obj_slime and obj_bat, instance_count(obj_enemy) adds up every enemy of every kind, while instance_count(obj_slime) counts slimes only.

You can name more than one object and it adds them up: instance_count(obj_slime, obj_bat) is the slimes and the bats together (a name given twice counts once).

An instance you destroyed with instance_destroy is still counted for the rest of that frame, because it finishes the frame first. The count goes down in the next frame.

Every object also has a built-in cap on this number - see instance_max for what it is and why checking it matters. Each object has its own cap, so for a parent the count can be bigger than the parent's own instance_max: it includes children, who have caps of their own.

Example

if (instance_count(obj_doc_enemy) < 6 && btn_pressed(BTN_A)) {
    instance_create(x, y, obj_doc_enemy);
}

Only spawns another obj_doc_enemy while fewer than 6 are currently alive.

On the GBA

Counts instances destroyed earlier in this same frame too - their slots are not freed until the frame ends (see instance_destroy). So this number only drops on the NEXT frame, and a loop waiting for it to reach zero never ends. Its own ceiling is instance_max(obj) - the two are meant to be read together: instance_max(obj) - instance_count(obj) is how many more can be created right now. That reading holds for an object with no children. If `obj` is a parent, the count includes every descendant, and each descendant has its own pool and its own instance_max, so the count can exceed instance_max(obj): the comparison can then call the parent full while its own pool still has room, never the other way round.

See also: instance_createinstance_maxinstance_nth